package test.algorithm.dp;

/**
 * @Projectname: leetCode
 * @Filename: Knapsack
 * @Author: FANSEA
 * @Date:2024/9/11 11:18
 */

/**
 * 背包问题
 */
public class Knapsack {
    public static void main(String[] args) {
        int[] weight = {1, 3, 4};
        int[] value = {15, 20, 30};
        int capacity = 4;
        int res = knapsack(weight, value, capacity);
        System.out.println(res);
    }

    // 计算得到最大价值
    private static int knapsack(int[] weight, int[] value, int capacity) {
        int[][] dp =new int[weight.length+1][capacity+1]; // dp[i][j]表示前i个物品在容量为j的情况下能获得的最大价值
        for (int i = 1; i <= weight.length; i++) {
            for (int j = 1; j <= capacity; j++)
                if (j < weight[i-1]){
                    dp[i][j] = dp[i-1][j];
                }else {
                    dp[i][j] = Math.max(dp[i-1][j],dp[i-1][j-weight[i-1]]+value[i-1]);
                }
        }
        return dp[weight.length][capacity];

    }
}
